package com.mjx.controller;

import com.mjx.Util.BeanFactory;
import com.mjx.entity.User;
import com.mjx.service.ChatService;
import com.mjx.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by meijingxiang on 2017/3/9.
 */
@Component
@ServerEndpoint(value = "/websocket/{uid}")
public class MyWebSocket {

    //静态变量，用来记录ç当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //系统用户
    private static User system = new User();

    //系统会话id
    private static final String SYSTEM_DEFAULT_CID = "public";

    private static final String SYSTEM_DEFAULT_UID = "system";

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //当前用户
    private User user;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

//    @Autowired    不能注入
    private ChatService chatService;

    private UserService userService;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String uid) throws UnsupportedEncodingException {
        //将需要的service手动注入
        initService();
        initSession(session);
        addOnlineCount();           //在线数加1

        user = userService.findUserById(uid);

        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            chatService.sendMessage(session, "欢迎" + user.getName(), system, SYSTEM_DEFAULT_CID);
        } catch (Exception e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        String cid = session.getQueryString();
        //群发消息
        try {
            chatService.sendMessage(webSocketSet, message,user, cid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     * */
     @OnError
     public void onError(Session session, Throwable error) {
     System.out.println("发生错误");
     error.printStackTrace();
     }


     private void initService(){
         chatService = (ChatService) BeanFactory.getBean("chatService");
         userService = (UserService) BeanFactory.getBean("userService");
     }

     private void initSession(Session session){
         this.session = session;
         webSocketSet.add(this);     //加入set中
     }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public ChatService getChatService() {
        return chatService;
    }

    public void setChatService(ChatService chatService) {
        this.chatService = chatService;
    }
}
